import { 
  useState, 
} from 'react';
import { 
  Button, 
  Input, 
  Loading, 
  Toast 
} from 'react-vant';
import { 
  ChatO, 
  UserO 
} from '@react-vant/icons';
import useTitle from '@/hooks/useTitle';
import { chat } from '@/llm';
import styles from './aiChat.module.css';

const AIChat = () => {
  useTitle('AI比价助手');
  
  const [input, setInput] = useState('');
  const [messages, setMessages] = useState([
    {
      role: 'assistant',
      content: '您好，我是AI比价助手，请问有什么可以帮助您的吗？'
    }
  ]);
  const [isSending, setIsSending] = useState(false);

  const handleSend = async () => {
    if (!input.trim()) {
      Toast.info({
        message: '内容不能为空'
      });
      return;
    }

    setIsSending(true);
    
    // 添加用户消息
    const userMessage = { role: 'user', content: input };
    const newMessages = [...messages, userMessage];
    setMessages(newMessages);
    setInput('');
    
    try {
      // 调用API
      const response = await chat(newMessages);
      if (response.code === 0) {
        setMessages([...newMessages, response.data]);
      } else {
        Toast.fail({
          message: 'API调用失败: ' + response.msg
        });
        console.error('API调用失败:', response.msg);
      }
    } catch (err) {
      Toast.fail({
        message: '发送失败，请重试'
      });
      console.error('发送失败:', err);
    } finally {
      setIsSending(false);
    }
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  return (
    <div className="flex flex-col h-all">
      <div className={`flex-1 ${styles.chatArea}`}>
        {messages.map((msg, index) => (
          <div
            key={index}
            className={
              msg.role === 'user' ? 
              styles.messageRight : 
              styles.messageLeft
            }
          >
            {msg.role === 'assistant' ? <ChatO /> : <UserO />}
            <div>{msg.content}</div>
          </div>
        ))}
      </div>
      
      <div className={`flex ${styles.inputArea}`}>
        <Input
          value={input}
          onChange={setInput}
          placeholder="请输入消息"
          className={`flex-1 ${styles.input}`}
          disabled={isSending}
          onKeyDown={handleKeyPress}
          type="textarea"
          autosize={{ minRows: 1, maxRows: 4 }}
        />
        <Button 
          type="primary" 
          onClick={handleSend}
          disabled={isSending}
          loading={isSending}
          loadingText="发送中"
        >
          发送
        </Button>
      </div>
      
      {isSending && (
        <div className={styles.fixedLoading}>
          <Loading type="ball" />
        </div>
      )}
    </div>
  );
};

export default AIChat;